//
//  StatusViewModel.swift
//  CXSwiftWB
//
//  Created by meidaeriOS on 2017/6/5.
//  Copyright © 2017年 meidaer. All rights reserved.
//

import UIKit

class StatusViewModel: NSObject {
    
    /// 模型对象
    var status: Status?
    
    /// 存储所有配图URL
    var thumbnail_pics: [URL]?
    
    /// 存储所有配图大图URL
    var bmiddle_pics: [URL]?
    
    init(status: Status) {
        self.status = status
        guard let urls = (status.retweeted_status != nil) ? status.retweeted_status?.pic_urls : status.pic_urls else
        {
            return
        }
        
        thumbnail_pics = [URL]()
        bmiddle_pics = [URL]()
        for dict in urls {
            // 处理缩略图
            var urlStr = dict["thumbnail_pic"] as? String
            let url = URL(string: urlStr ?? "")
            thumbnail_pics?.append(url!)
            
            guard let temp = urlStr, temp != "" else {
                return
            }
            urlStr = temp.replacingOccurrences(of: "thumbnail", with: "bmiddle")
            let url2 = URL(string: urlStr!)!
            bmiddle_pics?.append(url2)
        }
    }
    
    var souceText: String {
        guard let temp = status?.source, temp != "" else
        {
            return ""
        }
        
        // 找到开始的位置
        let startIndex = temp.range(of: "<")?.upperBound
        
        let endIndex = temp.range(of: "<", options: .backwards, range: nil, locale: nil)?.lowerBound
        let res = temp.substring(with: Range(uncheckedBounds: (lower: startIndex!, upper: endIndex!)))
        
        return "来自 " + res
    }
    /// 用户头像URL
    var avatarURL: URL
    {
        // 3.处理头像
        return URL(string: status?.user?.profile_image_url ?? "")!
    }
    
    var createdText: String{
        
        // 0.安全校验
        // 先检查created_at是否有值, 如果没有就进入else
        // 并且temp 不能是 "", 如果是""就进入else
        guard let temp = status?.created_at, temp != "" else
        {
            return ""
        }
        
        // 1.将发布微博的时间字符串转换为NSDate
        guard let createDate = Date.dataWithString(temp) else
        {
            return ""
        }
        
        // 2.利用微博发布的时间和当前本机的时间进行比较
        return createDate.desc
        
    }
    
    /// 认证图片
    var verifiedImage: UIImage?
    {
        //  4.处理认证图片
        switch status?.user?.verified_type ?? -1
        {
        case 0:
            // 个人认证
            return UIImage(named: "avatar_vip")
        case 2, 3, 5:
            // 企业认证
            return UIImage(named: "avatar_enterprise_vip")
        case 220:
            // 微博达人
            return UIImage(named: "avatar_grassroot")
        default:
            // 没有认证
            return nil
        }
    }
    
    /// 会员图片
    var mbrankImage: UIImage?
    {
        // 5.处理会员图标
        if (status?.user?.mbrank)! >= 1 && (status?.user?.mbrank)! <= 6
        {
            return  UIImage(named: "common_icon_membership_level\(String(describing: status?.user!.mbrank))")
        }
        return nil
    }
    

}
